package thread.futerAndCallable;

import java.util.Random;
import java.util.concurrent.*;

public class FutureTest {

	public static void main(String[] args) {
		ExecutorService service = Executors.newSingleThreadExecutor();
		class MyCallable implements Callable<String> {
			public String call() throws Exception {
				for(int i=0;i<10;i++)
				{
					Thread.sleep(300);
					System.out.println("calling " + i);					
				}
				return "hello";
			}
			
		}

		
		Future<String> future = service.submit(new Callable<String>(){
			public String call() throws Exception {
				for(int i=0;i<10;i++)
				{
					Thread.sleep(200);
					System.out.println("calling " + i);					
				}
				return "hello";
			}
			
		});
		
		try {
			//加上下面这句则暂停失败，还能看到上面打印的calling。
			//Thread.sleep(2000);			
			//future.cancel(false);
			//System.out.println(future.isCancelled());
			if(true){
				System.out.println("等待callable进行 运算....");
				System.out.println("运算结果为: "+future.get());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("end!");
		service.shutdown();


		/*CompletionService用于提交一组Callable任务，其take方法返回已完成的一个Callable任务对应的Future对象。
		好比我同时种了几块地的麦子，然后就等待收割。收割时，则是那块先成熟了，则先去收割哪块麦子。*/
		ExecutorService executorService=Executors.newFixedThreadPool(10);
		CompletionService<Integer> ecs = new ExecutorCompletionService<Integer>(executorService);
		for(int i=0;i<10;i++) {
			final Integer seq=i;
			ecs.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					int span= new Random().nextInt(3000);
					System.out.println("Sleeping time is : "+span );
					Thread.sleep(span);
					return seq;
				}
			});
		}

		try {
			for(int i=0;i<10;i++){
				Future<Integer> future2 = ecs.take();
				System.out.println(future2.get());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		executorService.shutdown();
	}

}